/**
 * 通用js方法封装处理
 * Copyright
 */
// 获取指定cookie
export function getCookie(name: string) {
  const cookies: any[] = document.cookie.split(';')
  // 修剪字符串两侧的空格
  name = name.trim()
  // 遍历cookie数组
  for (let i = 0; i < cookies.length; i++) {
    // 如果当前cookie的名称与要查找的名称相同，返回它的值
    if (cookies[i].split('=')[0] === name) {
      // 修剪字符串两侧的空格
      return cookies[i].split('=')[1] && cookies[i].split('=')[1].trim()
    }
  }
  // 如果没有找到，返回null
  return null
}
// 接口节流
export function apiThrottle<T extends (...args: any[]) => any>(fn: T, wait: number = 5000) {
  let timer = true
  return function (this: any, ...args: Parameters<T>) {
    if (timer) {
      timer = false
      fn.apply(this, args)
      setTimeout(() => {
        timer = true
      }, wait)
    }
  }
}
// 日期格式化
export function parseDate(time: any, pattern?: string) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
/**
 * 时间去除毫秒
 */
export function removeMillisecond(value: string) {
  if (/\.(\d{6})/.test(value)) {
    return value.replace(/\.(\d{6})/, '')
  } else if (/\.(\d{4})/.test(value)) {
    return value.replace(/\.(\d{4})/, '')
  }
  return value
}
/**
 * 时间去除毫秒
 */
export function removeYearMillisecond(value: string) {
  if (/^(\d{4}-)|(:\d{2}\.(\d{4,6}))/g.test(value)) {
    return value.replace(/^(\d{4}-)|(:\d{2}\.(\d{4,6}))/g, '')
  }
  return value
}
// 返回项目路径
export function getNormalPath(p: any) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p
  }
  const res = p.replace('//', '/')
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1)
  }
  return res
}
// 添加时间格式化
export function parseTime(time: number) {
  if (typeof time !== 'number') return time
  const d: number = Math.floor(time / 86400)
  const h: number = Math.floor((time % 86400) / 3600)
  const m: number = Math.floor((time % 3600) / 60)
  const s: number = time % 60
  let str = ''
  if (d > 0) {
    str += d + 'd'
  }
  if (h > 0) {
    str += h + 'h'
  }
  if (m > 0) {
    str += m + 'm'
  }
  if (s > 0) {
    str += s + 's'
  }
  return str
}

/**
 * 文件下载
 * @param url 下载地址
 * @param file_name 文件名
 */
export const download = async (file_url: string, file_name: string) => {
  // let url = file_url
  // const a = document.createElement('a')
  // a.href = url
  // a.download = file_name // 下载后文件名
  // a.style.display = 'none'
  // document.body.appendChild(a)
  // a.click() // 点击下载
  // document.body.removeChild(a) // 下载完成移除元素

  fetch(file_url)
    .then(response => response.blob()) // 获取Blob对象
    .then(blob => {
      // 创建一个指向Blob对象的URL
      const urlObject = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = urlObject;
      a.download = file_name.split('.')[0] + '.pdf';
      document.body.appendChild(a);
      a.click(); // 触发下载
      document.body.removeChild(a);
      // 释放URL对象
      URL.revokeObjectURL(urlObject);
    })
    .catch(error => {
      console.error('下载文件时出错:', error);
    });
}

//滚动条滚动到指定位置
export const scrollTopLocation = (domeRef: HTMLElement, scrollTopHeight?: number) => {
  nextTick(() => {
    if (domeRef) {
      domeRef.scrollTo({
        top: scrollTopHeight || 400,
        behavior: 'smooth', // 可选，平滑滚动
      });
    }
  })
}
